<template>
<div>
  <h1>用户管理</h1>
  <el-form :inline="true" :model="fromData" class="demo-form-inline">
   
    <el-form-item label="用户手机号查询">
        <el-input v-model="fromData.phone" placeholder="请输入用户手机号"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSelect">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="showAddDialog">添加</el-button>
      </el-form-item>
  </el-form>
  <el-table
    :data="dangqianyeData"
    style="width: 100%">
    <el-table-column
      label="用户id" align='center'  prop="id"
      width="180">
    </el-table-column>
    <el-table-column
    label="用户头像" align='center'>
    <template slot-scope="scope">
      <!-- 使用v-if确保在数据加载完成前不尝试渲染图像 -->
      <el-image v-if="isDataLoaded"
                style="width: 50px; height: 50px"
                :src="scope.row.avatar"
                fit="cover"
                :preview-src-list="[scope.row.avatar]">
      </el-image>
    </template>
  </el-table-column>
    <el-table-column
      label="用户姓名" align='center'  prop="name"
      >
    </el-table-column>
    <el-table-column
      label="用户年龄" align='center'  prop="age"
      >
    </el-table-column>
   
    <el-table-column
      label="用户性别" align='center' prop="gender"
      >
      <template slot-scope="scope">
        {{ scope.row.gender==1?'男':'女' }}
      </template>
    </el-table-column>
    <el-table-column
      label="用户手机" align='center'  prop="phone"
    >
    </el-table-column>
    <el-table-column align='center' label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="showEditDialog(scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div v-if="isDataLoaded">
  <el-pagination
    layout="prev, pager, next"
    @current-change='changepage'
    :page-count="maxPage"
    >
  </el-pagination>
</div>
<!-- 编辑对话框 -->
<el-dialog
      title="编辑用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="用户年龄">
          <el-input v-model.number="editForm.age"></el-input>
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio v-model="editForm.gender" label="1">男</el-radio>
          <el-radio v-model="editForm.gender" label="0">女</el-radio>
        </el-form-item>
        <el-form-item label="用户手机号">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" type="password">
          <el-input v-model="editForm.pwd" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
<!-- 添加信息框 -->
<!-- 添加对话框 -->
<el-dialog title="添加用户信息" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="fromData" label-width="100px">
        <!-- 表单上传头像区域 -->
        
        <el-form-item class="uploadPic">
        <el-upload
  class="avatar-uploader"
  ref="uploadComponent"
  action="http://localhost:8081/img/upload"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatarPic">
  <i v-else class="el-icon-plus avatar-uploader-icon">上传头像</i>
</el-upload></el-form-item>
          
        <el-form-item label="用户姓名">
          <el-input v-model="fromData.name"></el-input>
        </el-form-item>
        <el-form-item label="用户年龄">
          <el-input v-model.number="fromData.age"></el-input>
        </el-form-item>
        <el-form-item label="用户手机号">
          <el-input v-model="fromData.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="fromData.pwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="fromData.confirmPwd" show-password></el-input>
        </el-form-item>
        

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadFile">确 定</el-button>
      </span>
    </el-dialog>

</div>
</template>

<script>
import { computed } from 'vue';
import axios from 'axios';
import { baseUrl } from '../store/baseUrl';
// 创建一个新的 DTO 类型对象用于存储查询条件
const SysUserPageDto = {
  phone: ''
};
export default {
  name: 'User',
  data () { 
    return {
      fromData: {
          avatar:'',
          name:'',
          phone: '',
          pwd: ''
      },
    imageUrl:'',
    userList : [],
    dangqianpage:1,
    isDataLoaded: false,
    searchDto: { ...SysUserPageDto },
    editDialogVisible: false, // 控制编辑对话框的显示，
    addDialogVisible: false,
    editForm: {} // 编辑表单的数据模型
    };
  },
computed:{
  dangqianyeData(){
    let qishi =(this.dangqianpage-1)*10
    return this.userList.slice(qishi,qishi+10)
  },
  // 添加一个计算属性来控制是否数据已经加载完成
  isDataLoaded() {
      return this.userList.length > 0;
    },
   
},
created(){
  this.fetchData();
},
  methods: {
    fetchData() {
      axios.get(`${baseUrl}/sysuser/list`)
        .then(response => {
          this.userList = response.data.data;
          this.userList.forEach(user => {
            // 假设从后端返回的数据中，头像URL在一个叫做"avatar"的字段中
            user.avatar = `${baseUrl}${user.avatar}`;
          });
          this.maxPage = Math.ceil(this.userList.length / 10);
          // 设置数据加载标志
          this.isDataLoaded = true;
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    },
    fetchDataByPhone() {
      axios.post(`${baseUrl}/sysuser/pageLikePhone`, this.searchDto)
      .then(response => {
        this.userList = response.data.data;
        this.userList.forEach(user => {
          // 确保从后端返回的数据中，头像URL在一个叫做"avatar"的字段中
          user.avatar = `${baseUrl}${user.avatar}`;
        });
        this.maxPage = Math.ceil(this.userList.length / 10);
        this.dangqianpage = 1; // 重置当前页码为第一页
        // 设置数据加载标志
        this.isDataLoaded = true;
      })
        .catch(error => {
          console.error('There was an error!', error);
        });
    },
    onSelect() {
      this.searchDto.phone = this.fromData.phone;
      this.fetchDataByPhone(); // 执行模糊查询
    },
    showEditDialog(row) {
      this.editForm = { ...row }; // 复制用户信息到编辑表单
      this.editDialogVisible = true; // 显示编辑对话框
    },
    saveEdit() {
       if (this.editForm.pwd == null) {
        this.$message.error('密码不能为空！');
        return;
      }else{
      //发送更新请求
      axios.post(`${baseUrl}/sysuser/modifyById`, this.editForm)
        .then(() => {
          // 成功更新后，重新获取数据
          this.fetchData();
          this.editDialogVisible = false;
          this.$message.success('success!');
        })
        .catch(error => {
          console.error('Failed to update user:', error);
        });
      }
    },
    handleDelete (index, row) {
      // 实现删除功能
      // 确认对话框，确认是否删除
      this.$confirm('确定删除该用户信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      //发送删除请求
        axios.delete(`${baseUrl}/sysuser/removeById/${row.id}`) 
          .then(() => {
            // 删除成功后，重新获取数据
            this.fetchData();
          })
          .catch(error => {
            console.error('Failed to delete user:', error);
          });
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    // 添加信息
    // 显示添加信息框
    showAddDialog() {
      this.addDialogVisible = true;
    },
    beforeAvatarUpload(file) {
    // 只返回 true，因为我们将在点击“确定”时上传文件
    return true;
  },
  uploadFile() {
    // 获取上传组件实例
    const uploadInstance = this.$refs.uploadComponent;

    if (uploadInstance) {
      // 触发上传
      uploadInstance.submit();
      this.saveAdd();
    }
  },
    saveAdd() {
      if (this.fromData.pwd !== this.fromData.confirmPwd) {
        this.$message.error('密码与确认密码不一致！');
        return;
      }
      axios.post(`${baseUrl}/sysuser/add`, this.fromData)
        .then(response => {
          this.$message({
            message: response.data.msg,
            type: 'success'
          });
          this.addDialogVisible = false;
          this.fetchData();
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    },

     handleAvatarSuccess(res, file) {
      // 使用后端返回的路径作为图像的URL
      this.imageUrl = `${baseUrl}/${res.data}`;
      // 添加 avatar 字段到 formLabelAlign 对象中，使用后端返回的数据
      this.fromData.avatar = res.data;
    },
      beforeAvatarUpload(file) {
        this.fromData.avatar = file.name;
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isPNG) {
          this.$message.error('上传头像图片只能是 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isPNG && isLt2M;
      },
    changepage(page){
      this.dangqianpage=page
    }
  }
}

</script>
<style scoped>
  .el-table {
    margin: auto;
    margin-top: 20px;
  }
 .el-pagination{
  text-align: center;
  margin-top: 20px;
 
 }
 .avatarPic {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .el-icon-plus{
      font-size: 15px;
    }
</style>